package com.sdr.webCamera;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.dh.DpsdkCore.Dep_Info_t;
import com.dh.DpsdkCore.Device_Info_Ex_t;
import com.dh.DpsdkCore.Enc_Channel_Info_Ex_t;
import com.dh.DpsdkCore.Get_Channel_Info_Ex_t;
import com.dh.DpsdkCore.Get_Dep_Count_Info_t;
import com.dh.DpsdkCore.Get_Dep_Info_t;
import com.dh.DpsdkCore.IDpsdkCore;
import com.dh.DpsdkCore.Login_Info_t;
import com.dh.DpsdkCore.Return_Value_Info_t;
import com.dh.DpsdkCore.fDPSDKStatusCallback;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by homelajiang on 2016/7/6 0006.
 */
public class webCameraManager extends CordovaPlugin {
    private static final String TAG = "webCamera_TAG";
    static Return_Value_Info_t m_ReValue = new Return_Value_Info_t();
    static int m_nLastError = 0;
    static long m_loginHandle;

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (TextUtils.isEmpty(action)) {
            return false;
        }

        //just a test
        if (action.equals("test")) {
            Toast.makeText(cordova.getActivity(), "just a Test", Toast.LENGTH_SHORT).show();
            return true;
        }
        //初始化程序
        if (action.equals("init")) {
            initCamera();
            return true;
        }
        //登录
        if (action.equals("login")) {
            login(callbackContext, args.getString(0), args.getString(1), args.getString(2), args.getString(3));
            return true;
        }
        //获取根节点信息
        if (action.equals("getRootInfo")) {
            if (callbackContext != null) {
                Dep_Info_t temp = loadDGroupInfoLayered();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("szDepName", new String(temp.szDepName));
                jsonObject.put("szCoding", new String(temp.szCoding));
                callbackContext.success(jsonObject);
            }
            return true;
        }
        //获取组织/信息
        if (action.equals("getGroup")) {
            if (callbackContext != null) {
                Get_Dep_Info_t temp = getGroupList(args.getString(0));
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("szCoding", new String(temp.szCoding));
                jsonObject.put("nDepCount", temp.nDepCount);
                jsonObject.put("nDeviceCount", temp.nDeviceCount);

                JSONArray jsonArray1 = new JSONArray();
                for (Dep_Info_t dit : temp.pDepInfo) {
                    JSONObject jo = new JSONObject();
                    jo.put("szDepName", new String(dit.szDepName));
                    jo.put("szCoding", new String(dit.szCoding));
                    jsonArray1.put(jo);
                }
                jsonObject.put("pDepInfo", jsonArray1);

                JSONArray jsonArray2 = new JSONArray();
                for (Device_Info_Ex_t diet : temp.pDeviceInfo) {
                    JSONObject jo = new JSONObject();
                    jo.put("szId", new String(diet.szId));
                    jo.put("szName", new String(diet.szName));
                    jo.put("nFactory", diet.nFactory);
                    jo.put("szModel", diet.szModel);
                    jo.put("szUser", new String(diet.szUser));
                    jo.put("szPassword", new String(diet.szPassword));
                    jo.put("szIP", new String(diet.szIP));
                    jo.put("nDevType", diet.nDevType);
                    jo.put("nPort", diet.nPort);
                    jo.put("szLoginType", diet.szLoginType);
                    jo.put("szRegID", new String(diet.szRegID));
                    jo.put("nProxyPort", diet.nProxyPort);
                    jo.put("nUnitNum", diet.nUnitNum);
                    jo.put("nStatus", diet.nStatus);
                    jo.put("szCN", new String(diet.szCN));
                    jo.put("szSN", new String(diet.szSN));
                    jo.put("nRight", diet.nRight);
                    jo.put("szDevIP", new String(diet.szDevIP));
                    jo.put("nDevPort", diet.nDevPort);
                    jo.put("dev_Maintainer", new String(diet.dev_Maintainer));
                    jo.put("dev_MaintainerPh", new String(diet.dev_MaintainerPh));
                    jo.put("dev_Location", new String(diet.dev_Location));
                    jo.put("desc", new String(diet.desc));
                    jo.put("nEncChannelChildCount", diet.nEncChannelChildCount);
                    jo.put("iAlarmInChannelcount", diet.iAlarmInChannelcount);
                    jsonArray2.put(jo);
                }
                jsonObject.put("pDeviceInfo", jsonArray2);

                callbackContext.success(jsonObject);
            }
            return true;
        }
        //获取频道信息
        if (action.equals("getChannel")) {
            if (callbackContext != null) {
                Enc_Channel_Info_Ex_t[] ecInfo = getChannelList(args.getString(0),Integer.parseInt(args.getString(1)));
                JSONArray jsonArray = new JSONArray();
                for (Enc_Channel_Info_Ex_t eciet : ecInfo) {
                    JSONObject jo = new JSONObject();
                    jo.put("nCameraType", eciet.nCameraType);
                    jo.put("szId", new String(eciet.szId));//important
                    jo.put("szName", new String(eciet.szName));//important
                    jo.put("nRight", eciet.nRight);
                    jo.put("nChnlType", eciet.nChnlType);
                    jo.put("nStatus", eciet.nStatus);
                    jo.put("szChnlSN", new String(eciet.szChnlSN));
                    jo.put("szLatitude", new String(eciet.szLatitude));
                    jo.put("szLongitude", new String(eciet.szLongitude));
                    jo.put("szMulticastIp", new String(eciet.szMulticastIp));
                    jo.put("nMulticastPort", eciet.nMulticastPort);
                    jsonArray.put(jo);
                }
                callbackContext.success(jsonArray);
            }
            return true;
        }
        /**
         * 跳转到实时播放界面
         * channelName szName
         * channelId szId
         */
        if (action.equals("toRealPlay")) {
            openPlayActivity(args.getString(0), args.getString(1), true);
            if (callbackContext != null) {
                callbackContext.success();
            }
            return true;
        }
        //跳转到回放界面
        if (action.equals("toBackPlay")) {
            openPlayActivity(args.getString(0), args.getString(1), true);
            if (callbackContext != null) {
                callbackContext.success();
            }
            return true;
        }
        //登出
        if (action.equals("logout")) {
            logout();
            if(callbackContext!=null){
                callbackContext.success();
            }
            return true;
        }
        return false;
    }

    //初始化
    public static void initCamera() {
        //DPSDK_Create 在一个应用中只需调用一次，建议不要同时创建多份，在需要重新创建时也需要调用DPSDK_Destroy先释放
        m_nLastError = IDpsdkCore.DPSDK_Create(1, m_ReValue);//所有传入作为参数的变量在外部都需要初始化

        //注册平台状态（可选功能）
        //用户登录后平台sdk 会自动和服务器保持连接状态
        //平台sdk已经有重连机制，当重连成功后，如果用户注册了平台状态回调，平台sdk会将平台状态回调给用户，此时可进行业务调用，无需重新调用DPSDK_Login
        IDpsdkCore.DPSDK_SetDPSDKStatusCallback(m_ReValue.nReturnValue, new fDPSDKStatusCallback() {

            @Override
            public void invoke(int nPDLLHandle, int nStatus) {
                // TODO Auto-generated method stub
                Log.v("fDPSDKStatusCallback", "nStatus = " + nStatus);
            }
        });
    }

    //登录
    public void login(final CallbackContext callbackContext, final String... params) {
        cordova.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                Login_Info_t loginInfo = new Login_Info_t();

                loginInfo.szIp = params[0].getBytes();
                loginInfo.nPort = Integer.parseInt(params[1]);
                loginInfo.szUsername = params[2].getBytes();
                loginInfo.szPassword = params[3].getBytes();
                loginInfo.nProtocol = 2;

                int nRet = IDpsdkCore.DPSDK_Login(m_ReValue.nReturnValue, loginInfo, 10000);
                if (0 == nRet) {
                    IDpsdkCore.DPSDK_SetCompressType(m_ReValue.nReturnValue, 1);
                    m_loginHandle = 1;
                    if (callbackContext != null) {
                        callbackContext.success(nRet);
                    }
                } else {
                    m_loginHandle = 0;
                    callbackContext.error(nRet);
                }

            }
        });
    }

    //登出
    public static void logout() {
        if (m_loginHandle == 0) {
            return;
        }
        int nRet = IDpsdkCore.DPSDK_Logout(m_ReValue.nReturnValue, 10000);//登出平台

        if (0 == nRet) {//登出成功 设置已登出
            m_loginHandle = 0;
        }
    }

    //获取根节点信息
    public Dep_Info_t loadDGroupInfoLayered() {
        Dep_Info_t dInfo = new Dep_Info_t();
        IDpsdkCore.DPSDK_GetDGroupRootInfo(getDpsdkHandle(), dInfo);
        return dInfo;
    }

    //获取设备，组织列表
    public Get_Dep_Info_t getGroupList(String szCodingString) {
        Get_Dep_Count_Info_t gdcInfo = new Get_Dep_Count_Info_t();
        gdcInfo.szCoding = szCodingString.getBytes();
        IDpsdkCore.DPSDK_GetDGroupCount(getDpsdkHandle(), gdcInfo);

        Get_Dep_Info_t gdInfo = new Get_Dep_Info_t(gdcInfo.nDepCount, gdcInfo.nDeviceCount);
        gdInfo.szCoding = szCodingString.getBytes();
        IDpsdkCore.DPSDK_GetDGroupInfo(getDpsdkHandle(), gdInfo);
//        //组织信息
//        Dep_Info_t[] dInfo = gdInfo.pDepInfo;
//        //设备信息
//        Device_Info_Ex_t[] dInfo1 = gdInfo.pDeviceInfo;
        return gdInfo;
    }

    //获取通道信息
    public Enc_Channel_Info_Ex_t[] getChannelList(String szId, int nEncChannelChildCount) {
        Get_Channel_Info_Ex_t gcInfo = new Get_Channel_Info_Ex_t(nEncChannelChildCount);
        gcInfo.szDeviceId = szId.getBytes();
        IDpsdkCore.DPSDK_GetChannelInfoEx(getDpsdkHandle(), gcInfo);
        Enc_Channel_Info_Ex_t[] ecInfo = gcInfo.pEncChannelnfo;
        return ecInfo;
    }

    //打开实时/回放界面 szName szId
    public void openPlayActivity(String channelName, String channelId, boolean realPlay) {
        Intent intent = new Intent();
        intent.putExtra("channelName", channelName);
        intent.putExtra("channelId", channelId);
        if (realPlay) {
            intent.setClass(cordova.getActivity(), RealPlayActivity.class);
        } else {
            intent.setClass(cordova.getActivity(), BackPlayActivity.class);
        }
        cordova.getActivity().startActivity(intent);
    }

    static public int getDpsdkHandle() {
        if (m_loginHandle == 1) {
            return m_ReValue.nReturnValue;
        } else {
            return 0;
        }
    }

//    //保存登录信息
//    private void saveLoginInfo(){
//        SharedPreferences sp = cordova.getActivity().getSharedPreferences("LOGININFO", 0);
//        SharedPreferences.Editor ed = sp.edit();
//        StringBuilder sb = new StringBuilder();
//        sb.append(m_serverIp.getText().toString()).append(",").append(m_serverPort.getText().toString()).append(",")
//                .append(m_serverPassword.getText().toString()).append(",").append(m_serverUserName.getText().toString());
//        ed.putString("INFO", sb.toString());
//        ed.putString("ISFIRSTLOGIN", "false");
//        ed.commit();
//        Log.i("TestDpsdkCoreActivity", "saveLoginInfo" + sb.toString());
//    }

}
